/**
 * [倒计时对象]
 */
function CountDownT(){
  //服务器时间
  this.serverTime = null;
  //开始时间
  this.validTime = null;
  //结束时间
  this.expireTime = null;
  //倒计时剩余秒数
  this.leftsecond = 0;
  //是否准备开始
  this.isPrepare = false;
  //是否已结束
  this.isOver = false;
  //剩余小时数
  this.hour = 0;
  //剩余分钟数
  this.minute = 0;
  //剩余秒数
  this.second = 0;
  //剩余小时数
  this.viewHour = '0';
  //剩余分钟数
  this.viewMinute = '0';
  //剩余秒数
  this.viewSecond = '0';
}

/**
 * [设置过期时间]
 * @param {[type]} expireTime [过期时间，可为Date或者时间戳]
 * @param {[type]} param      [回写方法名]
 * @param {[type]} oriObj     [回写对象]
 * @param {[type]} validTime  [生效时间(若生效时间大于0，则优先倒计时生效时间)]
 */
CountDownT.prototype.setExpireTime = function(serverTime,expireTime,param,oriObj,validTime){
  let that = this;
  if (!(serverTime instanceof Date)) {
    let temp = serverTime;
    serverTime = new Date();
    serverTime.setTime(temp);
  }
  this.serverTime = serverTime;

  if (!(expireTime instanceof Date)) {
    let temp = expireTime;
    expireTime = new Date();
    expireTime.setTime(temp);
  }
  this.expireTime = expireTime;
 
  if(typeof(validTime)!='undefined'){//即将开始
    if (!(validTime instanceof Date)) {
      let temp = validTime;
      validTime = new Date();
      validTime.setTime(temp);
    }
    this.validTime = validTime;
    if(new Date()<this.validTime){
      this.isPrepare = true;
    }
  }
  this.setLeftTime(param,oriObj);
};

//设置剩余秒数
CountDownT.prototype.setLeftTime = function(param,oriObj){
  let that = this;
  let startDate = this.serverTime;
  let leftTime = this.expireTime.getTime() - startDate.getTime();
  if(this.isPrepare){
    leftTime = this.validTime.getTime() - startDate.getTime();
  }  
  if (leftTime <= 0) {
    if(this.isPrepare){
      this.isPrepare = false;
    }else//已结束
      this.isOver = true;
    oriObj.setData({
      [param]:that
    });
    return;
  }
  this.leftsecond = parseInt(leftTime / 1000);
  this.countDown(param,oriObj);
}

/**
 * [倒计时]
 * @return {[type]} [description]
 */
CountDownT.prototype.countDown = function(param,oriObj){
  let that = this;
  if(this.leftsecond <= 0){//倒计时结束
    if(this.isPrepare){//即将开始结束
      this.isPrepare = false;
      this.setLeftTime(param,oriObj);
    }else
      this.isOver = true;
    oriObj.setData({
      [param]:that
    });
    return;
  }
  this.hour = Math.floor(this.leftsecond / 3600);
  this.viewHour = this.hour<10?('0' + this.hour):this.hour;
  this.minute = Math.floor((this.leftsecond - this.hour * 3600) / 60);
  this.viewMinute = this.minute<10?('0' + this.minute):this.minute;
  this.second = Math.floor(this.leftsecond - this.hour * 3600 - this.minute * 60);
  this.viewSecond = this.second<10?('0' + this.second):this.second;
  this.leftsecond = this.leftsecond - 1;
  
  oriObj.setData({
    [param]:that
  });
  setTimeout(function(){    
    that.countDown(param,oriObj);
  },1000);
}

module.exports = CountDownT